import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/plan.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:ui';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/models/today_goal.dart';

// 虚线边框小部件
class DashedRect extends StatelessWidget {
  final Color color;
  final double strokeWidth;
  final double gap;
  final Widget child;
  final double borderRadius;

  const DashedRect({
    Key? key,
    required this.color,
    required this.strokeWidth,
    required this.gap,
    required this.child,
    required this.borderRadius,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(strokeWidth),
      child: CustomPaint(
        painter: DashedRectPainter(
          color: color,
          strokeWidth: strokeWidth,
          gap: gap,
          borderRadius: borderRadius,
        ),
        child: child,
      ),
    );
  }
}

class DashedRectPainter extends CustomPainter {
  final Color color;
  final double strokeWidth;
  final double gap;
  final double borderRadius;

  DashedRectPainter({
    required this.color,
    required this.strokeWidth,
    required this.gap,
    required this.borderRadius,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    final rect = Rect.fromLTWH(
      strokeWidth / 2,
      strokeWidth / 2,
      size.width - strokeWidth,
      size.height - strokeWidth,
    );

    final path = Path()
      ..addRRect(RRect.fromRectAndRadius(rect, Radius.circular(borderRadius)));

    final dashPath = Path();
    final dashLength = 5.0;

    for (PathMetric metric in path.computeMetrics()) {
      double distance = 0.0;
      while (distance < metric.length) {
        dashPath.addPath(
          metric.extractPath(distance, distance + dashLength),
          Offset.zero,
        );
        distance += dashLength + gap;
      }
    }

    canvas.drawPath(dashPath, paint);
  }

  @override
  bool shouldRepaint(DashedRectPainter oldDelegate) {
    return oldDelegate.color != color ||
        oldDelegate.strokeWidth != strokeWidth ||
        oldDelegate.gap != gap ||
        oldDelegate.borderRadius != borderRadius;
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Plan> _todayUncompletedPlans = [];
  List<Plan> _thisWeekPlans = [];
  List<Plan> _last30DaysPlans = [];
  List<TodayGoal> _todayGoals = [];

  @override
  void initState() {
    super.initState();
    _loadPlans();
  }

  void _loadPlans() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      // 首先更新超时的计划状态
      context.read<AwakBloc>().add(UpdateExpiredPlansEvent(currentUser.id!));

      context.read<AwakBloc>().add(
        FetchTodayUncompletedPlansEvent(currentUser.id!),
      );
      context.read<AwakBloc>().add(FetchThisWeekPlansEvent(currentUser.id!));
      context.read<AwakBloc>().add(FetchNotStartedPlansEvent(currentUser.id!));
      context.read<AwakBloc>().add(FetchLast30DaysPlansEvent(currentUser.id!));
      context.read<AwakBloc>().add(FetchTodayGoalsEvent(currentUser.id!));
    }
  }

  Map<String, Color> _getGoalColors(int index) {
    final colorSets = [
      {
        'background': Color(0xFFFEF463),
        'border': Color(0xFFD9B747),
      },
      {
        'background': Color(0xFFD3F524),
        'border': Color(0xFF89B72D),
      },
      {
        'background': Colors.white,
        'border': Color(0xFFB3B3B3),
      },
    ];
    return colorSets[index % colorSets.length];
  }

  String _getTodayDateString() {
    final now = DateTime.now();
    final months = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];

    String getOrdinalSuffix(int day) {
      if (day >= 11 && day <= 13) {
        return 'th';
      }
      switch (day % 10) {
        case 1: return 'st';
        case 2: return 'nd';
        case 3: return 'rd';
        default: return 'th';
      }
    }

    return '${months[now.month - 1]} ${now.day}${getOrdinalSuffix(now.day)}';
  }

  @override
  Widget build(BuildContext context) {
    final isTablet = DeviceUtils.isTablet(context);
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is TodayUncompletedPlansLoaded) {
          setState(() {
            _todayUncompletedPlans = state.plans;
          });
        } else if (state is ThisWeekPlansLoaded) {
          setState(() {
            _thisWeekPlans = state.plans;
          });
        } else if (state is NotStartedPlansLoaded) {
          setState(() {
          });
        } else if (state is Last30DaysPlansLoaded) {
          setState(() {
            // 只显示当前时间之前的计划（已经开始的计划）
            final now = DateTime.now();
            _last30DaysPlans = state.plans.where((plan) => plan.startTime.isBefore(now)).toList();
          });
        } else if (state is ExpiredPlansUpdated) {
          // 超时计划更新后，重新加载计划列表
          _loadPlans();
        } else if (state is TodayGoalsLoaded) {
          setState(() {
            _todayGoals = state.todayGoals;
          });
        } else if (state is TodayGoalsBatchDeleted) {
          // 批量删除后重新加载今日目标
          final currentUser = context.read<AwakBloc>().userRepository.currentUser;
          if (currentUser != null) {
            context.read<AwakBloc>().add(FetchTodayGoalsEvent(currentUser.id!));
          }
        }
      },
      child: Scaffold(
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(AwakImages.editBg),
              fit: BoxFit.cover,
            ),
          ),
          child: SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(height: 60.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox(width: 4.w),
                    Image.asset(AwakImages.cloudy),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _getTodayDateString(),
                          style: AwakText.body14Style.copyWith(fontSize: 10.sp),
                        ),
                        Text(
                          'Cloudy',
                          style: AwakText.body14Style.copyWith(
                            color: Colors.black.withOpacity(0.5),
                            fontSize: 10.sp,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(width: 2.w),
                    Image.asset(
                      AwakImages.awakTitle,
                      width: 171.w,
                      height: 56.h,
                    ),
                    SizedBox(width: 2.w),
                    GestureDetector(
                      onTap: () {
                        Beamer.of(context).beamToNamed(RouterNames.messageProfile);
                      },
                      child: Icon(AwakSvg.notification, size: 24.w, color: Colors.black),
                    ),
                    GestureDetector(
                      onTap: () {
                        Beamer.of(context).beamToNamed(RouterNames.addPlan);
                      },
                      child: Icon(AwakSvg.publish, size: 24.w, color: Colors.black),
                    ),
                    SizedBox(width: 8.w),
                  ],
                ),
                SizedBox(height: 20.h),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        'Not Started (${_todayUncompletedPlans.length})',
                        style: AwakText.body16Style.copyWith(
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20.h),
                Container(
                  height: isTablet ? 280.h : 233.h,
                  child: _todayUncompletedPlans.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                AwakImages.empty,
                                width: 80.w,
                                height: 80.h,
                              ),
                              SizedBox(height: 16.h),
                              Text(
                                'No plans for today',
                                style: AwakText.body16Style.copyWith(
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        )
                      : ListView.builder(
                          scrollDirection: Axis.horizontal,
                          padding: EdgeInsets.only(left: 16.w),
                          itemCount: _todayUncompletedPlans.length,
                          itemBuilder: (context, index) {
                            final plan = _todayUncompletedPlans[index];
                            return Padding(
                              padding: EdgeInsets.only(right: 16.w),
                              child: Stack(
                                children: [
                                  Image.asset(
                                    AwakImages.planBg,
                                    width: 254.w,
                                    height: isTablet ? 280.h : 233.h,
                                    fit: BoxFit.cover,
                                  ),
                                  Positioned(
                                    top: 20.h,
                                    left: 20.w,
                                    right: 30.w,
                                    bottom: 10.h,
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Container(
                                          width: 214.w,
                                          height: isTablet ? 160.h : 128.h,
                                          decoration: BoxDecoration(
                                            color: Colors.white,
                                            borderRadius: BorderRadius.circular(
                                              12.r,
                                            ),
                                            image: DecorationImage(
                                              image: AssetImage(plan.picture),
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),
                                        SizedBox(height: 10.h),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    plan.title,
                                                    style: AwakText.body14Style
                                                        .copyWith(
                                                          fontWeight:
                                                              FontWeight.bold,
                                                          fontSize: 14.sp,
                                                        ),
                                                    maxLines: 1,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                  ),
                                                  Text(
                                                    plan.formattedRemainingTime,
                                                    style: AwakText.body14Style
                                                        .copyWith(
                                                          fontWeight:
                                                              FontWeight.w500,
                                                          fontSize: 10.sp,
                                                          color: const Color(
                                                            0xFF666666,
                                                          ),
                                                        ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                Beamer.of(context).beamToNamed(
                                                  RouterNames.detailPlan,
                                                  data: plan,
                                                );
                                              },
                                              child: Container(
                                                padding: EdgeInsets.symmetric(
                                                  horizontal: 12.w,
                                                  vertical: 4.h,
                                                ),
                                                decoration: BoxDecoration(
                                                  color: const Color(0xFF8B58F5),
                                                  borderRadius:
                                                      BorderRadius.circular(90.r),
                                                  border: Border.all(
                                                    color: Colors.black,
                                                    width: 1.w,
                                                  ),
                                                ),
                                                child: Text(
                                                  'BEGIN',
                                                  style: AwakText.body14Style
                                                      .copyWith(
                                                        fontWeight:
                                                            FontWeight.w700,
                                                        fontSize: 12.sp,
                                                        color: Colors.white,
                                                      ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                ),
                SizedBox(height: 20.h),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        'Today\'s Goal',
                        style: AwakText.body16Style.copyWith(
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                    ),
                    Spacer(),
                    GestureDetector(
                      onTap: () => _showAdjustGoalBottomSheet(context),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 6.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFD2F427),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Row(
                          children: [
                            Text(
                              'ADJUST',
                              style: AwakText.body16Style.copyWith(
                                fontWeight: FontWeight.w500,
                                fontSize: 12.sp,
                              ),
                            ),
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 10.w,
                              color: Colors.black,
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(width: 16.w),
                  ],
                ),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        "This is today's goal plan. Don't forget it, please!",
                        style: AwakText.body14Style.copyWith(
                          fontWeight: FontWeight.w400,
                          color: const Color(0xFF666666),
                          fontSize: 11.sp,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 15.h),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: _todayGoals.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                AwakImages.empty,
                                width: 60.w,
                                height: 60.h,
                              ),
                              SizedBox(height: 12.h),
                              Text(
                                'No goals for today',
                                style: AwakText.body14Style.copyWith(
                                  color: Colors.grey,
                                  fontSize: 12.sp,
                                ),
                              ),
                            ],
                          ),
                        )
                      : Wrap(
                          spacing: 8.w,
                          runSpacing: 8.h,
                          children: _todayGoals.asMap().entries.map((entry) {
                            int index = entry.key;
                            TodayGoal goal = entry.value;
                            final colors = _getGoalColors(index);

                            return Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 12.w,
                                vertical: 8.h,
                              ),
                              decoration: BoxDecoration(
                                color: colors['background'],
                                borderRadius: BorderRadius.circular(100.r),
                                border: Border.all(
                                  color: colors['border']!,
                                  width: 1.w,
                                ),
                              ),
                              child: Text(
                                goal.name,
                                style: AwakText.body14Style.copyWith(
                                  fontWeight: FontWeight.w500,
                                  fontSize: 14.sp,
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                ),
                SizedBox(height: 20.h),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        'Week\'s Plan',
                        style: AwakText.body16Style.copyWith(
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                    ),
                    Spacer(),
                    GestureDetector(
                      onTap: () {
                        Beamer.of(context).beamToNamed(RouterNames.myPlan);
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 6.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFD2F427),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Row(
                          children: [
                            Text(
                              'MORE',
                              style: AwakText.body16Style.copyWith(
                                fontWeight: FontWeight.w500,
                                fontSize: 12.sp,
                              ),
                            ),
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 10.w,
                              color: Colors.black,
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(width: 16.w),
                  ],
                ),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        "This is week's plan. Don't forget it, please!",
                        style: AwakText.body14Style.copyWith(
                          fontWeight: FontWeight.w400,
                          color: const Color(0xFF666666),
                          fontSize: 11.sp,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 15.h),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: _thisWeekPlans.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                AwakImages.empty,
                                width: 80.w,
                                height: 80.h,
                              ),
                              SizedBox(height: 16.h),
                              Text(
                                'No plans for this week',
                                style: AwakText.body16Style.copyWith(
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        )
                      : GridView.builder(
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          padding: EdgeInsets.zero,
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3,
                                childAspectRatio: 0.9,
                                crossAxisSpacing: 12.w,
                                mainAxisSpacing: 10.h,
                              ),
                          itemCount: _thisWeekPlans.length > 6
                              ? 6
                              : _thisWeekPlans.length,
                          itemBuilder: (context, index) {
                            final plan = _thisWeekPlans[index];
                            return GestureDetector(
                              onTap: () {
                                Beamer.of(context).beamToNamed(
                                  RouterNames.detailPlan,
                                  data: plan,
                                );
                              },
                              child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  width: 110.w,
                                  height: 80.h,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(12.r),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.1),
                                        blurRadius: 10,
                                        offset: Offset(0, 4),
                                      ),
                                    ],
                                  ),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(12.r),
                                    child: Image.asset(
                                      plan.picture,
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                                SizedBox(height: 8.h),
                                Text(
                                  plan.title,
                                  style: AwakText.body14Style.copyWith(
                                    fontWeight: FontWeight.w500,
                                    fontSize: 12.sp,
                                  ),
                                  textAlign: TextAlign.center,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(height: 4.h),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      plan.isCompleted
                                          ? 'Completed ${plan.weekdayName}'
                                          : 'Unfinished ${plan.weekdayName}',
                                      style: AwakText.body14Style.copyWith(
                                        fontWeight: FontWeight.w400,
                                        color: const Color(0xFF666666),
                                        fontSize: 8.sp,
                                      ),
                                    ),
                                    SizedBox(width: 4.w),
                                    Image.asset(
                                      plan.isCompleted
                                          ? AwakImages.completed
                                          : AwakImages.notCompleted,
                                      width: 12.w,
                                      height: 12.h,
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            );
                          },
                        ),
                ),
                SizedBox(height: 20.h),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        'History List',
                        style: AwakText.body16Style.copyWith(
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.w),
                      child: Text(
                        "The system only records the target list for the past 30 days",
                        style: AwakText.body14Style.copyWith(
                          fontWeight: FontWeight.w400,
                          color: const Color(0xFF666666),
                          fontSize: 11.sp,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20.h),
                _last30DaysPlans.isEmpty
                  ? Center(
                      child: Padding(
                        padding: EdgeInsets.symmetric(vertical: 40.h),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              AwakImages.empty,
                              width: 100.w,
                              height: 100.h,
                            ),
                            SizedBox(height: 20.h),
                            Text(
                              'No history plans in the last 30 days',
                              style: AwakText.body16Style.copyWith(
                                color: Colors.grey,
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                  : Column(
                      children: _last30DaysPlans.map((plan) {
                        final isCompleted = plan.isCompleted;
                        return Padding(
                          padding: EdgeInsets.only(bottom: 16.h),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                padding: EdgeInsets.only(
                                  left: 2.w,
                                  right: 16.w,
                                  top: 2.h,
                                  bottom: 2.h,
                                ),
                                decoration: BoxDecoration(
                                  color: Colors.black,
                                  borderRadius: BorderRadius.circular(4.r),
                                ),
                                child: Row(
                                  children: [
                                    Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 6.w,
                                        vertical: 8.h,
                                      ),
                                      decoration: BoxDecoration(
                                        color: const Color(0xFFFEF463),
                                        borderRadius: BorderRadius.circular(4.r),
                                      ),
                                      child: Text(
                                        plan.weekdayName.substring(0, 3),
                                        style: AwakText.body14Style.copyWith(
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 16.w),
                                    Text(
                                      '${plan.endTime.month.toString().padLeft(2, '0')}.${plan.endTime.day.toString().padLeft(2, '0')}',
                                      style: AwakText.body14Style.copyWith(
                                        fontWeight: FontWeight.w500,
                                        fontSize: 12.sp,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 16.w),
                              Container(
                                width: 250.w,
                                padding: EdgeInsets.symmetric(
                                  horizontal: 10.w,
                                  vertical: 14.h,
                                ),
                                decoration: BoxDecoration(
                                  color: isCompleted ? Colors.white : Colors.grey.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(12.r),
                                  border: Border.all(
                                    color: isCompleted ? Colors.black : Colors.grey.withOpacity(0.4),
                                    width: 1.w,
                                  ),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      plan.title,
                                      style: AwakText.body14Style.copyWith(
                                        color: isCompleted ? Colors.black : Colors.grey[600],
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      plan.description,
                                      style: AwakText.body14Style.copyWith(
                                        color: isCompleted ? Colors.black.withOpacity(0.5) : Colors.grey[500],
                                        fontWeight: FontWeight.w400,
                                        fontSize: 12.sp,
                                      ),
                                      maxLines: null,
                                      overflow: TextOverflow.visible,
                                      softWrap: true,
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ),
                        );
                      }).toList(),
                    ),
                SizedBox(height: 120.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showAdjustGoalBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _AdjustGoalBottomSheet(
        onGoalsUpdated: () {
          // 弹窗关闭后重新加载今日目标
          final currentUser = context.read<AwakBloc>().userRepository.currentUser;
          if (currentUser != null) {
            context.read<AwakBloc>().add(FetchTodayGoalsEvent(currentUser.id!));
          }
        },
      ),
    );
  }
}

class _AdjustGoalBottomSheet extends StatefulWidget {
  final VoidCallback? onGoalsUpdated;

  const _AdjustGoalBottomSheet({this.onGoalsUpdated});

  @override
  _AdjustGoalBottomSheetState createState() => _AdjustGoalBottomSheetState();
}

class _AdjustGoalBottomSheetState extends State<_AdjustGoalBottomSheet> {
  List<TodayGoal> todayGoals = [];
  List<TodayGoal> displayGoals = []; // 用于显示的临时列表
  List<int> deletedGoalIds = [];

  @override
  void initState() {
    super.initState();
    _loadTodayGoals();
  }

  void _loadTodayGoals() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      context.read<AwakBloc>().add(FetchTodayGoalsEvent(currentUser.id!));
    }
  }

  Map<String, Color> _getGoalColors(int index) {
    final colorSets = [
      {
        'background': Color(0xFFFEF463),
        'border': Color(0xFFD9B747),
      },
      {
        'background': Color(0xFFD3F524),
        'border': Color(0xFF89B72D),
      },
      {
        'background': Colors.white,
        'border': Color(0xFFB3B3B3),
      },
    ];
    return colorSets[index % colorSets.length];
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is TodayGoalsLoaded) {
          setState(() {
            todayGoals = state.todayGoals;
            // 初始化显示列表，排除已删除的目标
            displayGoals = state.todayGoals.where((goal) => 
              !deletedGoalIds.contains(goal.id)
            ).toList();
          });
        }
      },
      child: Container(
      height: MediaQuery.of(context).size.height * 0.5,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: EdgeInsets.all(20.w),
            child: Row(
              children: [
                Text(
                  'REGULATED OBJECT',
                  style: AwakText.body16Style.copyWith(
                    fontWeight: FontWeight.w800,
                    fontSize: 18.sp,
                  ),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Icon(
                    Icons.close,
                    size: 24.w,
                    color: Colors.black,
                  ),
                ),
              ],
            ),
          ),

          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 今日目标标签列表
                  Wrap(
                    spacing: 8.w,
                    runSpacing: 8.h,
                    children: displayGoals.asMap().entries.map((entry) {
                      int index = entry.key;
                      TodayGoal goal = entry.value;
                      final colors = _getGoalColors(index);
                      return Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color: colors['background'],
                          borderRadius: BorderRadius.circular(100.r),
                          border: Border.all(
                            color: colors['border']!,
                            width: 1.w,
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              goal.name,
                              style: AwakText.body14Style.copyWith(
                                fontWeight: FontWeight.w500,
                                fontSize: 14.sp,
                              ),
                            ),
                            SizedBox(width: 8.w),
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  if (goal.id != null) {
                                    deletedGoalIds.add(goal.id!);
                                  }
                                  displayGoals.removeAt(index);
                                });
                              },
                              child: Icon(
                                Icons.close,
                                size: 16.w,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),

                  SizedBox(height: 30.h),

                  // Set Today's Goal 文字
                  Text(
                    'Set Today\'s Goal',
                    style: AwakText.body16Style.copyWith(
                      fontWeight: FontWeight.w600,
                      fontSize: 16.sp,
                    ),
                  ),

                  SizedBox(height: 15.h),

                  // 添加新目标按钮
                  GestureDetector(
                    onTap: () {
                      Beamer.of(context).beamToNamed(RouterNames.addGoal);
                    },
                    child: DashedRect(
                      color: Color(0xFFFF5350),
                      strokeWidth: 2.w,
                      gap: 4.w,
                      borderRadius: 100.r,
                      child: Container(
                        width: 200.w,
                        padding: EdgeInsets.symmetric(vertical: 14.h, horizontal: 6.w),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(100.r),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.add,
                              color: Color(0xFFFF5350),
                              size: 20.w,
                            ),
                            SizedBox(width: 8.w),
                            Text(
                              'Set New Goals',
                              style: AwakText.body14Style.copyWith(
                                color: Color(0xFFFF5350),
                                fontWeight: FontWeight.w600,
                                fontSize: 14.sp,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  Spacer(),

                  // 保存按钮
                  Container(
                    width: double.infinity,
                    margin: EdgeInsets.only(bottom: 30.h),
                    child: GestureDetector(
                      onTap: () async {
                        if (deletedGoalIds.isNotEmpty) {
                          context.read<AwakBloc>().add(DeleteTodayGoalsByIdsEvent(deletedGoalIds));
                        }
                        Navigator.pop(context);
                        // 延迟调用回调函数，确保删除操作完成
                        await Future.delayed(Duration(milliseconds: 100));
                        widget.onGoalsUpdated?.call();
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 16.h),
                        decoration: BoxDecoration(
                          color: Color(0xFFB6F558),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Center(
                          child: Text(
                            'Save Adjustments',
                            style: AwakText.body16Style.copyWith(
                              fontWeight: FontWeight.w600,
                              fontSize: 16.sp,
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ),
    );
  }
}
